<?php
/**
 * Object Relational Persistence Mapping Class for table: drug_material
 *
 *
 * @package	modules.dept_pharmacy.ordo
 * @author	viethd
 * @version $
 * @copyright 2009 LHV Company
 */
class DrugMaterial extends ORDataObject {

    /**#@+
     * Fields of table: drug_material mapped to class members
     */
    var $drug_material_id			= '';
    var $proprietary_name			= '';
    var $drug_original_name_id		= '';
    var $default_usage_id           = '';
    var $enum_unit_import_sell		= '';
    var $disable					= '';
    var $enum_item_type				= '';
    var $insurance_support  		= '';
    var $cancer_drug     			= '';
    var $include_children  		   	= '';
    var $made_in   					= '';
    var $price 						= '';
    var $dang_thuoc					= '';
    var $dong_goi					= '';
    var $chi_dinh  					= '';
    var $chong_chi_dinh    			= '';
    var $tac_dung_phu	  		   	= '';
    var $lieu_luong					= '';
  
    
    /**#@-*/


    /**
     * DB Table
     */
    var $_table = 'drug_material';

    /**
     * Primary Key
     */
    var $_key = 'drug_material_id';

    /**
     * Internal Name
     */
    var $_internalName = 'DrugMaterial';

    /**
     * Handle instantiation
     */
    function __construct() {
        parent::ORDataObject();
    }

    public function getSuggestedDrugMaterials($filterData, $needle, $limit, $short = true) {
        $condition = true;
        if (isset($filterData['enum_item_type']) &&  trim($filterData['enum_item_type']) !== "") {
            $condition = $condition. " AND (enum_item_type='" . $filterData['enum_item_type'] . "')";
        }

        if ($short == true) {
            $sql = array(
            'cols'  => "drug_material_id, proprietary_name, enum_unit_import_sell, price",
            'from'  => "$this->_table",
            'where' => "proprietary_name LIKE '" . $needle . "%' AND " . $condition,
            'limit' => "$limit"
            );
        } else {
            $sql = array(
            'cols'  => "drug_material_id, proprietary_name,
                        enum_unit_import_sell, usage_title_enum,
                        usage_num, dosage,dosage_title_enum, time, quantity_num,
                        quantity_title_enum, price",
            'from'  => "$this->_table t LEFT JOIN default_usage pd ON (t.default_usage_id=pd.default_usage_id) ",
            'where' => "proprietary_name LIKE '" . $needle . "%' AND " . $condition,
            'limit' => "$limit"
            );
        }

        $ds =& new Datasource_sql();
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        return $result;

    }

    public function isExist($phaDrugMaterialId, $proName) {
        $ds =& new Datasource_sql();
        $sql = array(
            'cols'  => "drug_material_id",
            'from'  => "$this->_table",
            'where' =>  "drug_material_id='" . $phaDrugMaterialId . "' AND proprietary_name='" . $proName . "'",
            'limit' => "1"
        );
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        if (empty($result)) {
            return false;
        }
        return true;

    }

    public function isValidType($phaDrugMaterialId, $enumItemType) {
        $ds =& new Datasource_sql();
        $sql = array(
            'cols'  => "drug_material_id",
            'from'  => "$this->_table",
            'where' =>  "drug_material_id='" . $phaDrugMaterialId . "' AND enum_item_type='" . $enumItemType . "'",
            'limit' => "1"
        );
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        if (empty($result)) {
            return false;
        }
        return true;

    }

    public function getDrugMaterialIdByName($name) {
        if (trim($name) == '') {
            return 0;
        }
        $ds =& new Datasource_sql();
        $sql = array(
            'cols'  => "drug_material_id",
            'from'  => "$this->_table",
            'where' =>  "proprietary_name='" . trim($name) . "'",
            'limit' => "1"
        );
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        if (empty($result)) {
            return 0;
        }
        return $result[0]['drug_material_id'];
    }
    public function getDrugMaterialIdByNameItemType($name, $enumItemType) {
        if (trim($name) == '') {
            return 0;
        }
        $ds =& new Datasource_sql();
        $sql = array(
            'cols'  => "drug_material_id",
            'from'  => "$this->_table",
            'where' =>  "proprietary_name='" . $name . "' AND enum_item_type=$enumItemType",
            'limit' => "1"
        );
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        if (empty($result)) {
            return 0;
        }
        return $result[0]['drug_material_id'];
    }
    
    
    
    public function getProprietaryName() {
    	return $this->proprietary_name;
    }
    
    public function listDrugMaterialInfo($idList) {
        $inCond = " IN(-1";
        foreach ($idList as $id) {
        	$inCond .= "," . $id;
        }
        $inCond .= ") ";
        
        $ds =& new Datasource_sql();
        $sql = array(
            'cols'  => "drug_material_id, proprietary_name, enum_item_type, made_in, include_children, insurance_support, cancer_drug, price",
            'from'  => "$this->_table",
            'where' =>  "drug_material_id ". $inCond
        );
        $ds->setup($this->_db, $sql);
        return $ds->toArray();
    }
	public function getTotalNumber(){
		$ds = new Datasource_sql();
		$sql = array(
            'cols'    => "count(drug_material_id) as total",
            'from'    => "$this->_table",
            'where'   => "disable =0 "
		);
		$ds->setup($this->_db, $sql);
		$result = $ds->toArray('total');
		return $result[0];
	}
	/*
	 * autocomplete name
	 */
	public function getDrugMaterialForAutoComplete($needle) {
		$ds =& new Datasource_sql();
		$sql = array(
            'cols'  => "drug_material_id, proprietary_name ",
            'from'  => $this->_table ,
            'where' => "disable =0 and proprietary_name LIKE '%$needle%' "
		);
		
		$ds->setup($this->_db, $sql);
		return $ds->toArray();
	}
	public function checkProprietaryNameEdit($name){
		$ds = new Datasource_sql();
		$sql = array(
            'cols'    => "proprietary_name",
            'from'    =>  $this->_table ,
            'where'   => " disable =0 and proprietary_name ='". $name."'"
		);
		$ds->setup($this->_db, $sql);
		$result = $ds->toArray('proprietary_name');
		if (sizeof($result) > 0) return false;
		return true;
	}
	public function checkNameDisable($name){
		$ds = new Datasource_sql();
		$sql = array(
            'cols'    => "drug_material_id",
            'from'    => $this->_table ,
            'where'   => "disable =1 "
		);
		$ds->setup($this->_db, $sql);
		$result = $ds->toArray('drug_material_id');
		return $result[0];
		
	}
	public function savedata($array){
		if($array['include_children']==NULL) $array['include_children']=0;
		if($array['cancer_drug']==NULL) $array['cancer_drug']=0;
		$data = array (
			'drug_material_id'   => $array['drug_material_id'],
            'proprietary_name'   => trim($array['proprietary_name']),
		    'enum_item_type'     => EnumerationConstant::PHA_ITEM_TYPE_DRUG_KEY,
            'dang_thuoc'     	 => $array['dang_thuoc'],
		    'enum_unit_import_sell'   => $array['enum_unit_import_sell'],
            'dong_goi'     		 => $array['dong_goi'],
		    'made_in'            => $array['made_in'],
            'include_children'   => $array['include_children'],
            'cancer_drug'		 => $array['cancer_drug'],
			'chong_chi_dinh'     => $array['chong_chi_dinh'],
			'chi_dinh'     		 => $array['chi_dinh'],
            'chong_chi_dinh'   	 => $array['chong_chi_dinh'],
            'tac_dung_phu'		 => $array['tac_dung_phu'],
			'lieu_luong'    	 => $array['lieu_luong'],
		);
		
		$this->populateArray($data);
		$this->persist();
		return $this->get_id();
	}
    public function getAllDrugMaterialName($name=null) {
        $ds = new Datasource_sql();
        $where = "disable = 0";
        if($name!=null){
            $where = "disable = 0 AND proprietary_name='".trim($name)."'";
        }
        $sql = array(
            'cols'      => "*",
            'from'      => $this->_table ,
            'where'     => $where,
            'orderby'   => "proprietary_name"
            );

        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        return $result;

    }
    public function checkDrugMaterialNamSameEdit($name, $id){
        $ds = new Datasource_sql();
        $sql = array(
            'cols'    => "proprietary_name",
            'from'    => $this->_table ,
            'where'   => "disable = 0 AND  proprietary_name ='". $name."' and drug_material_id<>".$id
        );
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray('name');
        if (sizeof($result) > 0) return false;
        return true;
    }
    public function updateDrugMaterial($Id=null) {
        $sql = "UPDATE $this->_table  set  disable= 1 WHERE $this->_key = $Id ";
        $result = $this->_execute($sql);
        return $result;
    }
    public function getDrugNameWithId($proname=null) {
    	$str="";
    	$DrugMaterialDrugOriginalNameOrdo = Celini::newORDO('DrugMaterialDrugOriginalName');
    	$DrugOriginalNameOrdo = Celini::newORDO('DrugOriginalName');
    	// get array drugoriginalname
    	$Id = $this->getDrugMaterialIdByName($proname);
    	
    	$idDrugOriginalName = $DrugMaterialDrugOriginalNameOrdo->getIdDrugOriginalName($Id);
      
    	for($i = 0; $i<count($idDrugOriginalName); $i++){
    		$name = $DrugOriginalNameOrdo->getNameById($idDrugOriginalName[$i]);
    		$str.= $name[0]['name'].', ';
    	}
      
        return $str;
    }
    
    public function saveToDB($_POST){
    	$DrugMaterialDrugOriginalNameOrdo = Celini::newORDO('DrugMaterialDrugOriginalName');
        $DrugOriginalNameOrdo = Celini::newORDO('DrugOriginalName');
    	$errorArr = array('code'=>0,'mess'=>'');
    	$arrayComponent = array();
    	// str contain value don't have in DrugOriginalName and show mess
    	//$str="";
    	$flag = false;
    	$originalFlag = true;
    	$array =  explode(",", $_POST['component']);
        
    	for($i=0; $i<=count($array); $i++){
                $idDrugOriginalName =0;
                if($array[$i]!=" " && $array[$i]!=null){
	                $idDrugOriginalName = $DrugOriginalNameOrdo->checkExitNameReturnId(trim($array[$i]));
	                if($idDrugOriginalName==null){
	                	$originalFlag = false;
	                	// $str.=$array[$i].',';
	                	 array_push($arrayComponent,$array[$i]);
	                }
                }
    	}
    	$errorArr['code'] = 0;
        $errorArr['str'] = implode(",", $arrayComponent);
        $errorArr['mess'] = L10nHelper::_('Add not successful');
    	// if have o com
    	
    	if($originalFlag){
    	$this->_db->BeginTrans();
        $idDrugMaterial = $this->savedata($_POST);
	        if($idDrugMaterial >0){
	            //save to table drug_material_drug_original_name
	            
	           
	           // print_r($array);
	            for($i=0; $i<=count($array); $i++){
	                $idDrugOriginalName =0;
	                $idDrugOriginalName = $DrugOriginalNameOrdo->checkExitNameReturnId(trim($array[$i]));
	                //  echo $idDrugOriginalName;
	                if($idDrugOriginalName >0){
	                    // echo $idDrugOriginalName;
	                   $flag= $DrugMaterialDrugOriginalNameOrdo->savedataFromDrugMaterial($idDrugMaterial,$idDrugOriginalName);
	                
	                }else{
	                	if(trim($array[$i])!=""){
	                       $str.=$array[$i].',';
	                	}
	                }
	            }
	            if($flag){
	                $this->_db->CommitTrans();
	            }else{
	                $this->_db->RollbackTrans();
	            }
	            $errorArr['code'] = 1;
	            $errorArr['total'] =$this->getTotalNumber();
	           // $errorArr['str'] = $str;
	            $errorArr['mess'] = L10nHelper::_('Insert successful');
	        }
    	}
        return $errorArr;
    }
    
    public function EditWithIdDrugMaterial($_POST){
        $errorArr = array('code'=>0,'mess'=>'');
        $DrugMaterialDrugOriginalNameOrdo = Celini::newORDO('DrugMaterialDrugOriginalName');
        $DrugOriginalNameOrdo = Celini::newORDO('DrugOriginalName');
        // str contain value don't have in DrugOriginalName and show mess
        $str="";
        $flag = false;
        $originalFlag = true;
        $array =  explode(",", $_POST['component']);

        for($i=0; $i<=count($array); $i++){
                $idDrugOriginalName =0;
                if($array[$i]!=" " && $array[$i]!=null){
                    $idDrugOriginalName = $DrugOriginalNameOrdo->checkExitNameReturnId(trim($array[$i]));
                    if($idDrugOriginalName==null){
                        $originalFlag = false;
                         $str.=$array[$i].',';
                    }
                }
        }
        $errorArr['code'] = 0;
        $errorArr['str'] = $str;
        $errorArr['mess'] = L10nHelper::_('Add not successful');
        if($originalFlag){
	        $this->_db->BeginTrans();
	        
	        if($this->checkDrugMaterialNamSameEdit($_POST['proprietary_name'],$_POST['drug_material_id'])){
	            if($this->savedata($_POST)){
	            	// get list drug name
	            	$array =  explode(",", $_POST['component']);
	            	//insert
	            	// get id of drug name
	            	// if id exit in table map do not anything
	            	// else delete
	            
	            	$idDrugOriginalName = array();
	            	for($i=0; $i<count($array); $i++){
	            	       array_push($idDrugOriginalName, $DrugOriginalNameOrdo->checkExitNameReturnId(trim($array[$i])));
	                    //check exit in table map
	            	}
	            
	               //insert
	                for($j=0; $j<count($idDrugOriginalName); $j++){
	                	if($DrugMaterialDrugOriginalNameOrdo->checkId($_POST['drug_material_id'],$idDrugOriginalName[$j])){
	                		if((int)$idDrugOriginalName[$j]>0){
	                		   $DrugMaterialDrugOriginalNameOrdo->savedataFromDrugMaterial($_POST['drug_material_id'],$idDrugOriginalName[$j]);
	                		}
	                	}
	                }
	            	$drugOriginalNameId = $DrugMaterialDrugOriginalNameOrdo->listDrugOriginalNameId($_POST['drug_material_id']);
	            	//delete
	              
	            	for($k = 0; $k<count($drugOriginalNameId);$k++){
	            	
	            		if($this->findKey($drugOriginalNameId[$k],$idDrugOriginalName)){
	            			//delete
	            			$DrugMaterialDrugOriginalNameOrdo->DelRow($_POST['drug_material_id'],$drugOriginalNameId[$k]);
	            		}
	            		
	            	}
		            $this->_db->CommitTrans();
		      
	                $errorArr['code'] = 1;
	                $errorArr['mess'] = L10nHelper::_('Edit successful');
	            }
	        }else{
	            $errorArr['code'] = 0;
	            $errorArr['mess'] = L10nHelper::_('This name has exit in database');
	        }
	        
          
        }
        
     
        return $errorArr;
    }
    
    private function findKey($item, $array){
    $flag= true;
   
    	for($i=0; $i<count($array); $i++){
    		if($item == $array[$i] && $array[$i]!=""){
    			return false;
    		}
    	}
        return $flag;
    }
     public function deleteWithIdDrugMaterial($_POST){
        $errorArr = array('code'=>0,'mess'=>'');
        $DrugMaterialDrugOriginalNameOrdo = Celini::newORDO('DrugMaterialDrugOriginalName');
        // str contain value don't have in DrugOriginalName and show mess
        $str="";
        $flag = false;
      
        
        if($_POST['id']!=null){
             $this->_db->BeginTrans();
             if($this->updateDrugMaterial($_POST['id'])){
             	$flag = $DrugMaterialDrugOriginalNameOrdo->deleteWithDrugMaterialId($_POST['id']);
             	if($flag){
             	    $this->_db->CommitTrans();
             	}else{
             		$this->_db->RollbackTrans();
             	}
                $errorArr['code'] = 1;
                $errorArr['total'] = $this->getTotalNumber();
                $errorArr['mess'] = L10nHelper::_('Delete successful');
             }else{
             	
                $errorArr['code'] = 0;
                $errorArr['mess'] = L10nHelper::_('Delete not successful');
             }
             
        }
        
     
        return $errorArr;
    }
    
    /**
     * Update list price of a give drug/material
     * @author hdviet
     *
     * @param $drugMaterialId
     * @param $price
     * @return unknown_type
     */
    public function updateListPrice($drugMaterialId, $price) {
        $sql = "UPDATE $this->_table  set  price= $price where $this->_key = $drugMaterialId ";
        $result = $this->_execute($sql);
        return $result;
    }
    /**
     * @author thucnt
     */
    public function getDrugMaterialSearch($data = null, $start = 0, $limit = 0) {
        $drugMaterialList = array();
    	$ds =& new  Datasource_sql();
    	$field = L10nHelper::getLocale();
    	$table = L10nHelper::L10nTable();
    	$strIn = '(';
    	//Get array drug_material_id
	    $sqlDrugMaterialId = array(
			                'cols'      =>  'DISTINCT dm.drug_material_id',
			                'from'      =>  $this->_table.' AS dm LEFT JOIN
			                                drug_material_drug_original_name AS dmo
		                                ON (dm.drug_material_id = dmo.drug_material_id) LEFT JOIN
			                                drug_original_name AS don
			                                ON (dmo.drug_original_name_id = don.drug_original_name_id)',
			    	        'where'     => 'dm.disable = 0 AND
			    	                        dm.proprietary_name LIKE \'%'.$data['proprietary_name'].'%\'',
			    	        'limit'     => $start.', '.$limit
			    	               );
        if ($data['original_name'] != '') {
            $sqlDrugMaterialId['where'] .=  ' AND don.disable = 0 AND don.name LIKE \'%'.$data['original_name'].'%\'';
        }
	    $ds->setup($this->_db, $sqlDrugMaterialId);
	    $drugMaterialIdArr = $ds->toArray('drug_material_id');
	         
	    if (!empty($drugMaterialIdArr)) {
            foreach ($drugMaterialIdArr as $value) {
                $strIn .= $value.', ';
            }
            $strIn = substr($strIn, 0, strlen($strIn)-2);
            $strIn .= ')';
    		//Get result
		    $sql = array(
		           'cols'      =>  'dm.drug_material_id, dm.proprietary_name,
		                                     dm.price, l.'.$field.' AS country, don.name AS original_name',
		           'from'      =>  $this->_table.' AS dm LEFT JOIN
		                           drug_material_drug_original_name AS dmo
		                           ON (dm.drug_material_id = dmo.drug_material_id) LEFT JOIN
		                           drug_original_name AS don
		                           ON (dmo.drug_original_name_id = don.drug_original_name_id) LEFT JOIN
		                           country AS c ON (dm.made_in = c.country_id) LEFT JOIN
		                           '.$table.' AS l ON (c.name = l.localization_id)',
		           'where'     => 'dm.drug_material_id IN '.$strIn,
		           'order'     => 'dm.proprietary_name');
	        if ($data['original_name'] != '') {
	            $sql['where'] .=  ' AND don.disable = 0 AND don.name LIKE \'%'.$data['original_name'].'%\'';
	        }
		                        
		    $ds->setup($this->_db, $sql);
		    $drugMaterialList = $ds->toArray();
	    }
        return $drugMaterialList;
    }
    public function getDrugMaterialSearchTotal($data = null) {
        $total = 0;
        $ds =& new  Datasource_sql();
        $field = L10nHelper::getLocale();
        $table = L10nHelper::L10nTable();
        //Get array drug_material_id
        $sqlDrugMaterialId = array(
                                'cols'      =>  'COUNT(DISTINCT dm.drug_material_id) as total',
                                'from'      =>  $this->_table.' AS dm LEFT JOIN
                                                drug_material_drug_original_name AS dmo
                                                ON (dm.drug_material_id = dmo.drug_material_id) LEFT JOIN
                                                drug_original_name AS don
                                                ON (dmo.drug_original_name_id = don.drug_original_name_id)',
                                'where'     => 'dm.disable = 0 AND
                                                dm.proprietary_name LIKE \'%'.$data['proprietary_name'].'%\'');
    	if ($data['original_name'] != '') {
            $sqlDrugMaterialId['where'] .=  ' AND don.disable = 0 AND don.name LIKE \'%'.$data['original_name'].'%\'';
        }
        $ds->setup($this->_db, $sqlDrugMaterialId);
        $total = $ds->toArray('total');
        $total = $total[0];
    	return $total;
    }
    
    function getMedicineListByName($needle) {
        $ds = new Datasource_sql();
        $sql = array(
            'cols'  => "d.drug_material_id, d.proprietary_name, d.enum_unit_import_sell,
                        o.name as drug_original_name, pd.usage_title_enum",
            'from'  => "$this->_table d
                            LEFT JOIN drug_original_name o ON (d.drug_original_name_id = o.drug_original_name_id)
                            LEFT JOIN default_usage pd ON (d.default_usage_id = pd.default_usage_id)",
            'where' => "d.proprietary_name LIKE '" . $needle . "%' AND d.disable = 0",
            'orderby'   => 'd.proprietary_name'
        );
        
        $ds->setup($this->_db,$sql);
        return $ds->toArray();
    }
    
    function delete($phaDrugId) {
        $sql = "UPDATE $this->_table SET disable = 1 WHERE drug_material_id = '$phaDrugId'";
        $this->_execute($sql);
    }
}
?>
